package com.example.demo.controller;

import com.example.demo.dao.entity.Blog;
import com.example.demo.dao.entity.Movie;
import com.example.demo.service.BlogService;
import com.example.demo.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/movie")
public class MovieController {
    @Autowired
    private MovieService movieService;

    /**
     * 查询电影列表
     * @param model
     * @param movie
     * @return
     */
    @GetMapping("/list")
    public String getMovieList(Model model, Movie movie) {
        List<Movie> list = null;
        if(movie.getName() != null && !"".equals(movie.getName() )) {
            list = movieService.lambdaQuery()
                    .like(Movie::getName,movie.getName() )
                    .eq(Movie::getStatus,0)
                    .list();
            model.addAttribute("title", movie.getName() );
        }else{
            list = movieService.lambdaQuery().eq(Movie::getStatus,0).list();
        }
        model.addAttribute("list", list);
        return "movie/list";
    }

    /**
     * 新增电影页面
     * @param model
     * @param movie
     * @param id
     * @return
     */
    @GetMapping("addpage")
    public String addpage(Model model, @ModelAttribute Movie movie, @RequestParam(value = "id",required = false) Integer id){
        if(!StringUtils.isEmpty(id)){
            Movie byId = movieService.getById(id);
            model.addAttribute("movie",byId);
        }
        return "movie/add";
    }

    /**
     * 新增或修改电影
     * @param model
     * @param movie
     * @param principal
     * @return
     */
    @PostMapping(value = {"/add", "/update"}, produces = "application/json")
    public String saveOrUpdate(Model model, Movie movie, Principal principal) {
        String loginName = principal.getName();
        Date now = new Date();
        movie.setCreatePerson(loginName);
        movie.setUpdatePerson(loginName);
        if(movie.getId() == null){
            movie.setCreateTime(now);
        }
        movie.setUpdateTime(now);
        movieService.saveOrUpdate(movie);
        return getMovieList(model,movie);
    }


    /**
     * 删除电影
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public String deleteMovieById( @PathVariable Long id) {
        //逻辑删除
        movieService.lambdaUpdate().eq(Movie::getId,id).set(Movie::getStatus,1).update();
        return "success";
    }
}
